#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/12/4 11:11
# @Author  : FuKai ZHANG
# @File    : send_email.py
# @Description :
import smtplib
from email.mime.text import MIMEText
from utils.Other_tools.allure_report_data import TestMetrics, AllureFileClean
from utils import config


class SendEmail:
    """ 发送邮箱 """

    def __init__(self, metrics: TestMetrics):
        self.metrics = metrics

    @classmethod
    def send_mail(cls, user_list: list, sub, content: str) -> None:
        """

        @param user_list: 发件人邮箱
        @param sub:
        @param content: 发送内容
        @return:
        """
        user = "FuKaiZHang" + "<" + config.email.send_user + ">"

        message = MIMEText(content, _subtype='plain', _charset='utf-8')
        # 邮件主题
        message['Subject'] = sub
        # 收件人
        message['To'] = ";".join(user_list)  # 分号连接
        server = smtplib.SMTP()
        # 连接服务器
        server.connect(config.email.email_host)
        # 登录服务器
        server.login(config.email.send_user, config.email.stamp_key)
        # 发送邮件
        server.sendmail(user, user_list, message.as_string())
        # 关闭连接
        server.close()

    def send_main(self) -> None:
        """
        发送邮件
        :return:
        """
        email = config.email.send_list
        user_list = email.split(',')  #

        sub = config.project_name + f"Version:{config.project_version}" + "web自动化测试结果"
        # 定义邮件模板，根据需要自行修改
        content = f"""
        各位领导、同事, 大家好:
            {config.project_name},version:{config.project_version},自动化用例执行完成，执行结果如下:
            用例运行总数: {self.metrics.total} 个
            通过用例个数: {self.metrics.passed} 个
            失败用例个数: {self.metrics.failed} 个
            异常用例个数: {self.metrics.broken} 个
            跳过用例个数: {self.metrics.skipped} 个
            成  功   率: {self.metrics.pass_rate} %

        jenkins地址：your_jenkins_url
        详细情况可登录jenkins平台查看，非相关负责人员可忽略此消息。谢谢。
        测试执行人：{config.tester_name}
        """
        self.send_mail(user_list, sub, content)


if __name__ == '__main__':
    SendEmail(AllureFileClean().get_case_count()).send_main()
